package com.shruijin.wy.thread.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j
public class CyclicBarrierExample2 {


    private final static int totalCount=20;
    private static CyclicBarrier cyclicBarrier =new  CyclicBarrier(5,()->{
        log.info("callback is running!");
    });

    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newCachedThreadPool();

        for (int i=0;i<totalCount;i++){
            final  int threadNum  = i;
            //Thread.sleep(1000);
            exec.execute(()->{
                try{
                    race2(threadNum);
                } catch (Exception e){
                    log.error("exception",e);
                } finally {

                }
            });
        }
        log.info("finished!");
        exec.shutdown();
    }

    private  static void race2(int threadNum) throws Exception{
        Thread.sleep(100);
        log.info("thread {} is ready!!!",threadNum);
        try{
            cyclicBarrier.await(2000, TimeUnit.MILLISECONDS);
        } catch (BrokenBarrierException | TimeoutException e){
            //log.warn("BrokenBarrierException",e);
        }

        log.info("{} resume!!!",threadNum);
    }
}
